package com.example.zxingdemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {
    @Bind(R.id.text)
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

    }

    // 你也可以使用简单的扫描功能，但是一般扫描的样式和行为都是可以自定义的，这里就写关于自定义的代码了
// 你可以把这个方法作为一个点击事件
    public void customScan() {
        new IntentIntegrator(this)
                .setOrientationLocked(false)
                .setCaptureActivity(CustomScanActivity.class) // 设置自定义的activity是CustomActivity
                .initiateScan(); // 初始化扫描

    }

    @Override
// 通过 onActivityResult的方法获取 扫描回来的 值
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (intentResult != null) {
                if (intentResult.getContents() == null) {
                    Toast.makeText(this, "内容为空", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, "扫描成功", Toast.LENGTH_LONG).show();
                    // ScanResult 为 获取到的字符串
                    String ScanResult = intentResult.getContents();
                    text.setText(ScanResult);
                }
            } else {
                super.onActivityResult(requestCode, resultCode, data);
            }
        } else if (resultCode == 2) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("1");
            //将扫描出的信息显示出来
            text.setText(scanResult);
        }

    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button:
                customScan();
                break;
        }
    }
}
